<template>
  <!-- 上传双签合同组件 -->
  <div class="layout-content">
    <div class="upload-double-Sign">
      <a-space>
        <a-button v-if="!prePage && imgList.length == 0" @click="toBack"
          >返回修改</a-button
        >
        <c-upload
          :disabled="imgList.length >= 9"
          type="button"
          @change="uploadImg"
          accept="application/pdf,image/jpeg,image/png"
          buttonName="点击上传"
          buttonType="primary"
          multiple
        ></c-upload>
        <span class="info"
          ><a-icon class="icon" type="info-circle" />最多可上传9个文件</span
        >
        <p class="inline  fs-10" v-if="imgList.length >= 1">
          (<span class="primary"
            >{{ imgList.length > 9 ? 9 : imgList.length }}/9</span
          >)
        </p>
      </a-space>
      <div class="upload-content">
        <a-tabs
          v-if="imgList.length > 0"
          v-model="activeKey"
          hide-add
          type="editable-card"
          class="imgTabs"
          size="small"
          @edit="onTabsEdit"
        >
          <a-tab-pane
            v-for="item in imgList"
            :key="item.id"
            :tab="item.title"
            :closable="item.closable"
          >
            <div class="previewImg tc" v-if="item.sourceUrl != ''">
              <iframe
                frameborder="0"
                v-if="item.fileType == 'application/pdf'"
                id="previewPdf"
                :src="pdfBaseUrl + 'file=' + item.sourceUrl"
                height="1200"
                width="100%"
              >
              </iframe>
              <img v-else :src="item.sourceUrl" alt="" />
            </div>
          </a-tab-pane>
        </a-tabs>
        <div class="empty" v-else></div>
        <div class="pagination-wrap"></div>
      </div>
      <div class="upload-submit-wrap tc">
        <a-space v-if="imgList.length > 0">
          <a-button v-if="!prePage" @click="toBack">返回修改</a-button>
          <a-button
            class="upload-submit"
            type="primary"
            @click="toGeneratedContract"
            >确认生成合同
          </a-button></a-space
        >
      </div>
    </div>
  </div>
</template>
<script>
import cUpload from "@/components/upload";
import globalSite from "@/config/globalSite";
import { filterOption } from "../common/public";
import { getCurIdentity } from "@/util/common";
import {
  buyerContractListUploadContract,
  sellseContractListUploadContract,
  buyerOrderUploadContract,
  sellerOrderUploadContract
} from "@/api/contract";
export default {
  props: {
    page: {
      type: String,
      default: ""
    }
  },
  components: {
    cUpload
    // cpdfPreview
  },
  data() {
    return {
      fileType: "", //上传文件的类型
      activeKey: 0, //当前tab
      imgList: [], //图片显示列表
      imgFileList: [], //图片文件列表
      imgTotalLength: 0, //当前上传总图片数量
      resultPageTitle: "成功上传双签合同", //组件标题
      prePage: "" //上一个跳转页面
    };
  },

  watch: {
    imgList: function(val) {
      this.imgList = val;
    }
  },
  computed: {
    identity() {
      return getCurIdentity(); //1买家，2卖家
    },
    createContractOrder() {
      return this.$storage.s_get("createContractOrder");
    },
    createContractparams() {
      return this.$storage.s_get("createContractparams");
    },
    contractPageParmas() {
      return {
        contractId: this.$route.query.contractId,
        contractVersion: this.$route.query.contractVersion
      };
    },
    pdfBaseUrl() {
      return globalSite.pdfBaseUrl;
    }
  },
  created() {
    this.activeKey = this.imgList[0] ? this.imgList[0].id : 0;
    this.toTop();
    this.getInt();
  },
  methods: {
    filterOption,
    toBack() {
      this.$emit("onStepChange", 0);
    },
    // 获取初始化数据
    getInt() {
      let query = this.$route.query;
      this.prePage = query.prePage;
    },
    //回到顶部
    toTop() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    },
    //上传合同
    uploadImg(file) {
      let files = file; //应该重新获取
      files = Array.prototype.slice.call(files); //全部转化为数组
      this.imgFileList = this.imgFileList.concat(files);
      for (let i = 0; i < file.length; i++) {
        let obj = {
          title: file[i].name,
          sourceUrl: URL.createObjectURL(file[i]),
          id: file[i].lastModified,
          fileType: file[i].type
        };
        this.objToHeavy(obj, this.imgList);
      }

      if (this.imgList.length > 9) {
        this.imgList.slice(0, 9);
        this.imgList = this.imgList.filter(function(value, index) {
          return index < 9;
        });
        this.$message.error("最多可上传9个文件");
      }
      this.activeKey = this.imgList[this.imgList.length - 1].id;
    },

    // 对象去重
    objToHeavy(obj, arr) {
      let isExist = false;
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].id === obj.id) {
          isExist = true;
          break;
        }
      }
      return !isExist && arr.push(obj);
    },
    //操作tab
    onTabsEdit(targetKey, action) {
      this[action](targetKey);
    },

    //删除图片
    remove(targetKey) {
      let activeKey = this.activeKey;
      let lastIndex;
      this.imgList.forEach((item, i) => {
        if (item.id === targetKey) {
          lastIndex = i - 1;
        }
      });
      const imgList = this.imgList.filter(pane => pane.id !== targetKey);
      const imgFileList = this.imgFileList.filter(
        item => item.lastModified !== targetKey
      );
      if (imgList.length && activeKey === targetKey) {
        if (lastIndex >= 0) {
          activeKey = imgList[lastIndex].id;
        } else {
          activeKey = imgList[0].id;
        }
      }
      this.imgList = imgList;
      this.activeKey = activeKey;
      this.imgFileList = imgFileList;
    },

    //对象传入转换formdata
    objFormData(obj, formData) {
      Object.keys(obj).forEach(key => {
        formData.append(key, obj[key]);
      });
      return formData;
    },

    fileFormData(formData) {
      this.imgFileList.forEach(file => {
        formData.append("file", file);
      });
      return formData;
    },

    contractListPageToGeneratedContract() {
      let requesFun;
      this.identity === 1
        ? (requesFun = buyerContractListUploadContract)
        : (requesFun = sellseContractListUploadContract);
      const formData = new FormData();
      //其他对象数据：
      this.objFormData(this.contractPageParmas, formData);
      //图片数据：
      this.fileFormData(formData);
      requesFun(formData)
        .then(res => {
          //跳转成功页面
          this.$message.success("操作成功");
          this.$emit("onStepChange", 2, [res]);
        })
        .finally(() => {});
    },
    orderPageToGeneratedContract() {
      let requesFun;
      const formData = new FormData();
      let objParmasArr = this.filterOption(
        [this.createContractparams],
        item => {
          return {
            signPlace: item.signPlace ? item.signPlace : "",
            signDate: this.$timeToTimestamp(item.signDate, 10)
              ? this.$timeToTimestamp(item.signDate, 10)
              : "",
            deliveryDate: this.$timeToTimestamp(item.deliveryDate, 10)
              ? this.$timeToTimestamp(item.deliveryDate, 10)
              : "",
            deliveryPlace: item.deliveryPlace ? item.deliveryPlace : "",
            deliveryPlaceType: item.deliveryPlaceType,
            contractCode: item.contractCode ? item.contractCode : "",
            contractCodeType: item.contractCodeType,
            priceType: item.priceType,
            categoryId: item.categoryId,
            dealCompanyId: item.dealCompanyId,
            beforeChangeCompanyId: item.beforeChangeCompanyId,
            currentCompanyId: item.currentCompanyId
          };
        }
      );
      let order = JSON.stringify(
        this.filterOption(this.createContractOrder, item => {
          return {
            version: item.version,
            orderId: item.orderId
          };
        })
      );

      this.objFormData(
        {
          ...objParmasArr[0],
          orders: order
        },
        formData
      );

      //图片数据：
      this.fileFormData(formData);
      this.identity === 1
        ? (requesFun = buyerOrderUploadContract)
        : (requesFun = sellerOrderUploadContract);
      requesFun(formData)
        .then(res => {
          this.$message.success("操作成功");
          //跳转成功页面
          this.$emit("onStepChange", 2, [res]);
        })
        .finally(() => {});
    },
    //生成合同
    toGeneratedContract() {
      if (this.prePage == "contractListPage") {
        // 合同列表上传双签合同
        this.contractListPageToGeneratedContract();
      } else {
        // 订单列表上传双签合同
        this.orderPageToGeneratedContract();
      }
    }
  }
};
</script>
<style scoped lang="scss">
@mixin custom_w_h() {
  width: 100%;
  height: 100%;
}
@mixin custom_m_h() {
  min-height: 600px;
}

.upload-double-Sign {
  .upload-content {
    margin: 10px;
  }
  .imgTabs {
    min-height: 500px;
    margin-top: 20px;
  }
  .pagination-wrap {
    margin-top: 20px;
    @include custom_w_h();
  }
  .info {
    font-size: 13px;
    .icon {
      color: #e6a23c;
      margin-right: 2px;
    }
  }
  .upload-submit-wrap {
    @include custom_w_h();
    margin: 30px 0;
  }
  .empty {
    @include custom_m_h();
  }
}
</style>
